package com.star.message.biz;

import com.google.common.collect.Sets;
import com.star.common.core.contract.enums.ResultCodeEnum;
import com.star.common.core.contract.exception.ServiceException;
import com.star.common.kit.contract.enums.language.RealLanguageTypeEnum;
import com.star.common.sms.factory.SmsFactory;
import com.star.message.contract.param.UserSmsConfigParam;
import com.star.message.repository.model.UserSmsConfigBO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 消息中心之短信服务
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/11/29 17:24
 */
@Service
@RequiredArgsConstructor
public class MessageSmsBizService {

    private final SmsFactory smsFactory;

    /**
     * 发送短信
     *
     * @param tenantId     租户id
     * @param languageCode 语言
     * @param countryCode  国家码(中国的话传86)
     * @param phone        手机号
     * @param codeMap      短信验证码code
     */
    public void sendSms(String tenantId, String languageCode, String countryCode, String phone, Map<String, String> codeMap) {
        UserSmsConfigBO userSmsConfigBO = getUserSmsConfigOrDefault(tenantId, languageCode);
        //发送短信，创建默认的短信发送方式
        Boolean flag=smsFactory.buildSmsClient(userSmsConfigBO.getPlatform())
                .sendSingle(countryCode + phone, userSmsConfigBO.getTemplateCode(), codeMap, userSmsConfigBO.getSignName());
    }


    /**
     * 获取用户短信配置，如果没有则获取默认配置英文（EN）
     *
     * @param tenantId     租户id
     * @param languageCode 语言编码
     * @return 用户短信配置
     */
    private UserSmsConfigBO getUserSmsConfigOrDefault(String tenantId, String languageCode) {
        List<UserSmsConfigBO> userSmsConfigBOList = UserSmsConfigBO.repository().list(UserSmsConfigParam.builder()
                .tenantId(tenantId)
                .languageCodeIn(Sets.newHashSet(languageCode, RealLanguageTypeEnum.EN.getCode()))
                .build());
        if (CollectionUtils.isEmpty(userSmsConfigBOList)) {
            //请配置默认模板
            throw new ServiceException(ResultCodeEnum.SMS_TEMPLATE_NOT_CONFIGURED);
        }
        //默认既有英文EN，也有当前要查询的语言
        if (userSmsConfigBOList.size() > 1) {
            return userSmsConfigBOList.stream()
                    .filter(userEmailConfigBO -> !RealLanguageTypeEnum.EN.getCode().equals(userEmailConfigBO.getLanguageCode()))
                    .findFirst()
                    //基本上不会出现下面报错，因为上面已经判断了
                    .orElseThrow(() -> new ServiceException(ResultCodeEnum.SMS_TEMPLATE_NOT_CONFIGURED));
        }
        //只有当前查询的语言，也可能当前查询的语言是英文EN
        return userSmsConfigBOList.getFirst();
    }
}
